package com.nch.haitonghop.data;

import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;

import com.nch.haitonghop.MyApp;
import com.nch.haitonghop.R;
import com.nch.haitonghop.others.Utils;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by nguyenconghuy on 12/30/14.
 */
public class DataManager {

    static final String kSourceKey = "sck";
    static final String kLastTimeUpdateServerKey = "ltusk";
    static final int kInvalidVersion = -1;
    static final int kDurationBetweenUpdateServer = 60*3600;

    private static DataManager instance = null;
    DataManagerDelegate delegate;

    int currentSourceVersion;
    ArrayList<SourceEntity> sourcesArray;

    DataManager() {
        currentSourceVersion = kInvalidVersion;
        sourcesArray = new ArrayList<SourceEntity>();
    }

    public static DataManager getInstance() {
        if(instance == null) {
            instance = new DataManager();
        }
        return instance;
    }

    public void setDelegate(DataManagerDelegate delegate) {
        this.delegate = delegate;
    }

    public ArrayList<SourceEntity> getSourcesArray() {
        return sourcesArray;
    }

    public void loadRemoteSource() {
        SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(MyApp.getInstance().getApplicationContext());
        String jsonString = preference.getString(kSourceKey, null);

        if(jsonString == null) {
            jsonString = Utils.readStringFromRaw(MyApp.getInstance().getResources(), R.raw.hai);
        }

        parseRemoteSource(jsonString);

        long lastTimeUpdateServer = preference.getLong(kLastTimeUpdateServerKey, 0);
        long currentTime = new Date().getTime()/1000;
        long durationFromLastUpdate = currentTime - lastTimeUpdateServer;
//        Log.d("", "lastTimeUpdateServer: " +lastTimeUpdateServer + ", currentTime: " + currentTime + ", durationFromLastUpdate: "+durationFromLastUpdate);

        if(durationFromLastUpdate > kDurationBetweenUpdateServer) {
//            Log.d("", "loadRemoteSourceFromServer");
            loadRemoteSourceFromServer();

            SharedPreferences.Editor editor = preference.edit();
            editor.putLong(kLastTimeUpdateServerKey, currentTime);
            editor.commit();
        }


    }

    void loadRemoteSourceFromServer() {
        GetSourceListAsyncTask getSourceListAsyncTask = new GetSourceListAsyncTask();
        getSourceListAsyncTask.execute();
    }

    private class GetSourceListAsyncTask extends AsyncTask<Void, Integer, String> {

        @Override
        protected String doInBackground(Void... params) {
            HttpClient httpClient = new DefaultHttpClient();

            String urlString = MyApp.getInstance().getString(R.string.link);

            HttpGet httpGet = new HttpGet(urlString);

            String responseString = null;
            try {
                HttpResponse response = httpClient.execute(httpGet);

                StatusLine statusLine = response.getStatusLine();
                if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    response.getEntity().writeTo(out);
                    out.close();
                    responseString = out.toString();
//                    Log.d("", "Finish get source list success: " + responseString);


                } else{
                    //Closes the connection.
//                    Log.d("", "Finish get photo list fail");
                    response.getEntity().getContent().close();
                    throw new IOException(statusLine.getReasonPhrase());
                }

            } catch (ClientProtocolException e) {
                e.printStackTrace();

            } catch (IOException e) {
                e.printStackTrace();
            }
            return responseString;
        }

        protected void onPostExecute(String result) {
            if(isCancelled() == false) {
                if(result != null) {
                    parseRemoteSource(result);
                }
            }
        }
    }

    void parseRemoteSource(String jsonString) {

        try {
            JSONObject jsonObject = new JSONObject(jsonString);

            int version = kInvalidVersion;

            version = jsonObject.getInt("version");
            if(version > currentSourceVersion) {
                if(currentSourceVersion != kInvalidVersion) {
                    SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(MyApp.getInstance().getApplicationContext());
                    SharedPreferences.Editor editor = preference.edit();
                    editor.putString(kSourceKey, jsonString);
                    editor.commit();
                }
                currentSourceVersion = version;
            }
            else {
                if(delegate != null) {
                    delegate.dataManagerDidLoadRemoteSourceFail();
                }
                return;
            }

            JSONArray pagesArray = jsonObject.getJSONArray("pages");
            sourcesArray.clear();

            for(int i = 0; i < pagesArray.length(); i++) {
                JSONObject pageObject = pagesArray.getJSONObject(i);
                SourceEntity sourceEntity = new SourceEntity();
                sourceEntity.iconString = pageObject.getString("icon");
                sourceEntity.title = pageObject.getString("title");
                sourceEntity.link = pageObject.getString("link");

                sourcesArray.add(sourceEntity);
            }

            if(delegate != null) {
                delegate.dataManagerDidLoadRemoteSourceSuccess();
            }

        } catch (JSONException e) {
            if(delegate != null) {
                delegate.dataManagerDidLoadRemoteSourceFail();
            }
            e.printStackTrace();
        }
    }

    public interface DataManagerDelegate {
        void dataManagerDidLoadRemoteSourceSuccess();
        void dataManagerDidLoadRemoteSourceFail();
    }

}
